package com.kye.express.business.order_list.subfragment;

import android.app.Activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.base.utils.DateUtils;
import com.kye.base.utils.GsonUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.business.order_detail.OrderDetailActivity;
import com.kye.express.business.order_list.subfragment.viewbinder.OrderListItemViewBinder;
import com.kye.express.business.score.ScoreActivity;
import com.kye.express.databinding.FragmentOrderListTakenBinding;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.UserSession;
import com.kye.model.base.PageInfo;
import com.kye.model.bean.order.OrderItemBean;
import com.kye.model.bean.order.OrderListResultBean;
import com.kye.model.bean.user.User;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import net.yslibrary.android.keyboardvisibilityevent.util.UIUtil;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 29/12/2017
 * @updated : 29/12/2017
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public class OrderListTakenFragment extends BaseAppCompatFragment implements OrderListTakenContract.OrderListTakenView, OrderListItemViewBinder.OnItemListener {

    private static final String DATE_PICKER_DIALOG = "DATE_PICKER_DIALOG";
    private static final int REQUEST_CODE_SCORE = 3001;
    protected FragmentOrderListTakenBinding binding;
    protected OrderListTakenContract.OrderListTakenPresenter presenter;
    protected MultiTypeAdapter adapter;

    protected final int QUERY_DATE_FROM = 0;
    protected final int QUERY_DATE_TO = 1;

    public static OrderListTakenFragment newInstance() {
        Bundle args = new Bundle();
        OrderListTakenFragment fragment = new OrderListTakenFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order_list_taken, container, false);
        initViews(view, savedInstanceState);
        return view;
    }

    private void initViews(View view, Bundle savedInstanceState) {
        binding = DataBindingUtil.bind(view);
        binding.setEnableQuery(false);
        adapter = new MultiTypeAdapter();
        adapter.register(OrderItemBean.class, new OrderListItemViewBinder(this));
        binding.orderList.setLayoutManager(new LinearLayoutManager(getActivity()));
        HorizontalDividerItemDecoration itemDecoration = new HorizontalDividerItemDecoration.Builder(getContext())
                .color(getResources().getColor(R.color.window_background))
                .size((int) UIUtil.convertDpToPx(getContext(), 0.5f)).build();
        binding.orderList.addItemDecoration(itemDecoration);
        binding.orderList.setAdapter(adapter);

        binding.setQueryDateFrom(new Date());
        binding.setQueryDateTo(new Date());
        binding.setEnableQuery(true);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        presenter = new OrderListTakenContract.OrderListTakenPresenter();
        presenter.bind(this);
        presenter.onCreate(savedInstanceState);
        initEvents(savedInstanceState);
    }

    private void initEvents(Bundle savedInstanceState) {
        RxView.clicks(binding.llErrorServerCustom.btErrorServerRetry)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llErrorNetCustom.btErrorNetRetry)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llEmptyCustom.llEmpty)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.tvDateFrom)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        showDateSelectDialog(QUERY_DATE_FROM);
                    }
                });
        RxView.clicks(binding.tvDateTo)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        showDateSelectDialog(QUERY_DATE_TO);
                    }
                });
        RxView.clicks(binding.btQuery)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Logger.d("query");
                        if (binding.statusLayout.isContentShown()) {
                            binding.refreshLayout.autoRefresh();
                        } else {
                            binding.statusLayout.showLoadingView();
                        }
                    }
                });
        binding.refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                presenter.refresh(binding.getQueryDateFrom(), binding.getQueryDateTo());
            }

            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                presenter.loadMore(binding.getQueryDateFrom(), binding.getQueryDateTo());
            }
        });
    }

    @Override
    protected void initDataFirstTime(boolean isForceUpdate, @Nullable Bundle savedInstanceState) {
        binding.statusLayout.showLoadingView();
        presenter.getUserInfo();
    }

    @Override
    public void refreshInitSuccess(OrderListResultBean orderListResultBean) {
        List<OrderItemBean> data = orderListResultBean.getData();
        if (data == null || data.size() <= 0) {
            binding.statusLayout.showEmptyView();
        } else {
            binding.statusLayout.showContentView();
            adapter.setItems(data);
            adapter.notifyDataSetChanged();
            binding.refreshLayout.setEnableLoadmore(data.size() >= PageInfo.SIZE_DEFAULT);
        }
    }

    @Override
    public void refreshInitFailed(String msg) {
        ToastManager.showCenter(msg, Toast.LENGTH_SHORT);
        binding.statusLayout.showErrorServerView();
    }

    @Override
    public void refreshInitFailed(Throwable e) {
        ToastManager.showCenter(e.getMessage(), Toast.LENGTH_SHORT);
        binding.statusLayout.showErrorNetworkView();
    }

    @Override
    public void refreshSuccess(OrderListResultBean orderListResultBean) {
        List<OrderItemBean> data = orderListResultBean.getData();
        binding.refreshLayout.finishRefresh(true);
        binding.refreshLayout.setEnableLoadmore(data.size() >= PageInfo.SIZE_DEFAULT);
        if (data == null || data.size() <= 0) {
            binding.statusLayout.showEmptyView();
        } else {
            adapter.setItems(data);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void refreshFailed(String msg) {
        ToastManager.showCenter(msg, Toast.LENGTH_SHORT);
        binding.refreshLayout.finishRefresh(false);
    }

    @Override
    public void refreshFailed(Throwable e) {
        ToastManager.showCenter(e.getMessage(), Toast.LENGTH_SHORT);
        binding.refreshLayout.finishRefresh(false);
    }

    @Override
    public void loadMoreSuccess(OrderListResultBean orderListResultBean) {
        List<OrderItemBean> data = orderListResultBean.getData();
        binding.refreshLayout.finishLoadmore(true);
        List<OrderItemBean> items = (List<OrderItemBean>) adapter.getItems();
        int startPosition = items.size();
        items.addAll(orderListResultBean.getData());
        adapter.notifyItemRangeInserted(startPosition, items.size());
        binding.refreshLayout.setEnableLoadmore(data.size() >= PageInfo.SIZE_DEFAULT);
    }

    @Override
    public void loadMoreFailed(String msg) {
        ToastManager.showCenter(msg, Toast.LENGTH_SHORT);
        binding.refreshLayout.finishLoadmore(false);
    }

    @Override
    public void loadMoreFailed(Throwable e) {
        ToastManager.showCenter(e.getMessage(), Toast.LENGTH_SHORT);
        binding.refreshLayout.finishLoadmore(false);
    }

    @Override
    public void onUser(User user) {
        if (user.isLogin()) {
            binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
                @Override
                public void onLoading() {
                    presenter.refreshInit(binding.getQueryDateFrom(), binding.getQueryDateTo());
                }
            });
            presenter.refreshInit(binding.getQueryDateFrom(), binding.getQueryDateTo());
            binding.setEnableQuery(true);
        } else {
            binding.statusLayout.showCustomView();
            binding.setEnableQuery(false);
        }
    }

    private void showDateSelectDialog(@IntRange(from = 0, to = 1) final int type) {
        int year;
        int monthOfYear;
        int dayOfMonth;
        Calendar calendar = Calendar.getInstance();
        if (type == QUERY_DATE_FROM) {
            if (binding.getQueryDateFrom() != null) {
                calendar.setTime(binding.getQueryDateFrom());
            }
        } else {
            if (binding.getQueryDateFrom() != null) {
                calendar.setTime(binding.getQueryDateTo());
            }
        }
        year = calendar.get(Calendar.YEAR);
        monthOfYear = calendar.get(Calendar.MONTH);
        dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.set(year, monthOfYear, dayOfMonth);
                        switch (type) {
                            case QUERY_DATE_FROM:
                                onSelectQueryDateFrom(calendar);
                                break;
                            case QUERY_DATE_TO:
                                onSelectQueryDateTo(calendar);
                                break;
                        }
                    }
                },
                year,
                monthOfYear,
                dayOfMonth
        );
        datePickerDialog.vibrate(true);
        datePickerDialog.setVersion(DatePickerDialog.Version.VERSION_1);
        datePickerDialog.showYearPickerFirst(true);
        datePickerDialog.show(getActivity().getFragmentManager(), DATE_PICKER_DIALOG);
    }

    private void onSelectQueryDateFrom(final Calendar calendarFrom) {
        Observable.just(binding.getQueryDateTo())
                .subscribeOn(Schedulers.io())
                .map(new Function<Date, Calendar>() {
                    @Override
                    public Calendar apply(Date date) throws Exception {
                        return DateUtils.dateToCalendar(date);
                    }
                })
                .map(new Function<Calendar, Boolean>() {
                    @Override
                    public Boolean apply(Calendar calendarTo) throws Exception {
                        return DateUtils.testLeftLessOrEqualToRight(calendarFrom, calendarTo);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        Logger.d("select date : " + aBoolean);
                        if (!aBoolean) {
                            ToastManager.show(getActivity(), "日期错误", Toast.LENGTH_SHORT);
                        } else {
                            binding.setQueryDateFrom(calendarFrom.getTime());
                        }
                    }
                });
    }

    private void onSelectQueryDateTo(final Calendar calendarTo) {
        Observable.just(binding.getQueryDateFrom())
                .subscribeOn(Schedulers.io())
                .map(new Function<Date, Calendar>() {
                    @Override
                    public Calendar apply(Date date) throws Exception {
                        return DateUtils.dateToCalendar(date);
                    }
                })
                .map(new Function<Calendar, Boolean>() {
                    @Override
                    public Boolean apply(Calendar calendarFrom) throws Exception {
                        return DateUtils.testLeftLessOrEqualToRight(calendarFrom, calendarTo);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        Logger.d("select date : " + aBoolean);
                        if (!aBoolean) {
                            ToastManager.show(getActivity(), "日期错误", Toast.LENGTH_SHORT);
                        } else {
                            binding.setQueryDateFrom(calendarTo.getTime());
                        }
                    }
                });
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        presenter.onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        presenter.unbind();
        super.onDestroy();
    }

    @Override
    public void onError() {

    }

    @Override
    public void onError(String msg) {

    }

    @Override
    public void onLoading() {

    }

    @Override
    public void onLoaded() {

    }

    @Override
    public void onItemOrderClicked(OrderItemBean item) {
        /**
         * todo : 详情
         */
        UserSession.getInstance()
                .getUserForRx()
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<User>() {
                    @Override
                    public void accept(User user) throws Exception {
                        Intent intent = OrderDetailActivity.newStartIntent(getActivity(), user.getPhone(), item.getOrderCode(), item.getScoreCode());
                        startActivity(intent);
                    }
                });
    }

    @Override
    public void onItemOrderScoreClicked(OrderItemBean item) {
        Logger.d("onItemOrderScoreClicked : " + GsonUtils.toJsonString(item, true));
        /**
         * todo : 评分
         */
        Intent intent = ScoreActivity.newStartIntentForScoreWayBill(getActivity(), item.getOrderCode());
        startActivityForResult(intent, REQUEST_CODE_SCORE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SCORE: {
                Logger.d("onActivityResult resultCode : " + resultCode);
                if (resultCode == Activity.RESULT_OK) {
                    /**
                     * todo : 完成评分，刷新数据
                     */
                    binding.refreshLayout.autoRefresh();
                }
                break;
            }
        }
    }

    public Date getDateFrom() {
        return binding.getQueryDateFrom();
    }

    public Date getDateTo() {
        return binding.getQueryDateFrom();
    }
}
